package org.company.management.ui;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import org.company.management.controller.ScheduleJpaController;
import org.company.management.entity.EmployeeSchedule;
import org.company.management.entity.Schedule;
import org.company.management.utilities.EmployeeEditingSupport;
import org.company.management.utilities.FromToEditingSupport;
import org.company.management.utilities.Strings;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.CellLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.EditorPart;
import org.eclipse.wb.swt.ResourceManager;
import org.eclipse.wb.swt.layout.grouplayout.GroupLayout;
import org.eclipse.wb.swt.layout.grouplayout.LayoutStyle;

/**
 * @author Paner
 *
 */
public class EditScheduleEditor extends EditorPart implements SelectionListener {
	
	public static final String ID = Strings.editscheduleEditorId;
	private Table table;
	private TableViewer _tableViewer;
	private Button _saveButton;
	private Combo _scheduleCombo;

	/* 
	 * Constructor, sets title image for editor
	 */
	public EditScheduleEditor() {
		setTitleImage(ResourceManager.getPluginImage(Strings.pluginId, Strings.homePicture16x16));

	}

	@Override
	public void doSave(IProgressMonitor monitor) {
		// TODO Auto-generated method stub

	}

	@Override
	public void doSaveAs() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void init(IEditorSite site, IEditorInput input)
			throws PartInitException {
		setSite(site);
		setInput(input);

	}

	@Override
	public boolean isDirty() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isSaveAsAllowed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void createPartControl(Composite parent) 
	{
		createControls(parent);
		createColumns(parent);
		createLayout(parent);
		fillTable();		
		
	}
	
	/*
	 * Creates widgets
	 */
	private void createControls(Composite parent) 
	{
		_tableViewer = new TableViewer(parent, SWT.BORDER | SWT.FULL_SELECTION);
		table = _tableViewer.getTable();
		table.setLinesVisible(true);
		table.setHeaderVisible(true);
		
		_saveButton = new Button(parent, SWT.NONE);
		_saveButton.setText(Strings.add);
		_saveButton.addSelectionListener(this);
		
		_scheduleCombo = new Combo(parent, SWT.NONE);
		_scheduleCombo.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Schedule schedule = (Schedule) ((Combo)e.getSource()).getData();
				loadModel(schedule);
			}
		});
		
	}
	
	/*
	 * Creates the columns of the schedule table
	 */
	private void createColumns(final Composite parent)
	{
		//First column is for employee last name
		TableViewerColumn col = createTableViewerColumn(Strings.name, 100, 0);
		col.setLabelProvider(new CellLabelProvider() {
			@Override
			//John
			public void update(ViewerCell cell) {
				cell.setText(((EmployeeSchedule) cell.getElement()).getEmployeeid().getLastname());
			}
			
		});
		col.setEditingSupport(new EmployeeEditingSupport(_tableViewer));

		List<String> colNames = generateColumnDayNames();
		
		//Day column starting index
		int dayCount = 1;
		for(String day : colNames)
		{
			col = createTableViewerColumn(day, 100, dayCount);
			final int identifier = dayCount;
			col.setLabelProvider(new CellLabelProvider() {
				@Override
				//John
				public void update(ViewerCell cell)
				{
					final int dayIdentifier = identifier - 1;
					String text = "";
					String test = ((EmployeeSchedule) cell.getElement()).getEmployeeScheduleInfoList().get(dayIdentifier).getFromTo();
					if(test != null)
					{
						text = ((EmployeeSchedule) cell.getElement()).getEmployeeScheduleInfoList().get(dayIdentifier).getFromTo();
					}
					
					cell.setText(text);
				}
			});
			col.setEditingSupport(new FromToEditingSupport(_tableViewer, identifier-1));
			
			dayCount++;
		}
		
	}
	
	/*
	 * Creates layout
	 */
	private void createLayout(Composite parent) 
	{
		GroupLayout gl_parent = new GroupLayout(parent);
		gl_parent.setHorizontalGroup(
			gl_parent.createParallelGroup(GroupLayout.TRAILING)
				.add(gl_parent.createSequentialGroup()
					.addContainerGap(508, Short.MAX_VALUE)
					.add(_saveButton)
					.addContainerGap())
				.add(table, GroupLayout.DEFAULT_SIZE, 594, Short.MAX_VALUE)
				.add(gl_parent.createSequentialGroup()
					.addContainerGap(377, Short.MAX_VALUE)
					.add(_scheduleCombo, GroupLayout.PREFERRED_SIZE, 143, GroupLayout.PREFERRED_SIZE)
					.add(74))
		);
		gl_parent.setVerticalGroup(
			gl_parent.createParallelGroup(GroupLayout.LEADING)
				.add(GroupLayout.TRAILING, gl_parent.createSequentialGroup()
					.add(_scheduleCombo, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
					.add(10)
					.add(table, GroupLayout.DEFAULT_SIZE, 421, Short.MAX_VALUE)
					.addPreferredGap(LayoutStyle.RELATED)
					.add(_saveButton)
					.add(0))
		);
		parent.setLayout(gl_parent);
		
	}
	
	/*
	 * Fills the schedule combo with schedules
	 */
	private void fillTable() 
	{
		try
		{
			ScheduleJpaController scheduleDao = new ScheduleJpaController();

			for(Schedule schedule : scheduleDao.findScheduleEntities())
			{
				_scheduleCombo.add(schedule.getDate());
				_scheduleCombo.setData(schedule);
			}
		}
		catch(Exception ex)
		{
			//throw;
		}
		
		_tableViewer.setContentProvider(new ArrayContentProvider());

	}

	//Create the columns for the table
	private List<String> generateColumnDayNames()
	{
		List<String> colNames = new ArrayList<String>();
		
		Locale grLocale = new Locale(Strings.el, Strings.GR);
		Calendar cal = new GregorianCalendar();
		
		//Assign dates to columns
		for(int i = 0; i<32; i++)
		{
			SimpleDateFormat formatter =  new SimpleDateFormat(Strings.dayMonthYear, grLocale);
			String dateNow = formatter.format(cal.getTime());
			colNames.add(dateNow);
			cal.add(Calendar.DAY_OF_YEAR, 1);

		}
		
		return colNames;
	}

	/*
	 * Enable column editing 
	 */
	private TableViewerColumn createTableViewerColumn(String title, int bound, final int colNumber)
	{
		//Set table column properties
		final TableViewerColumn viewerColumn = new TableViewerColumn(_tableViewer, SWT.NONE);
		final TableColumn column = viewerColumn.getColumn();
		column.setText(title);
		column.setWidth(bound);
		column.setResizable(true);
		column.setMoveable(true);
		
		return viewerColumn;
	}

	@Override
	public void widgetSelected(SelectionEvent e) 
	{
		Object selectedWidget = e.getSource();
		if (selectedWidget == _saveButton)
		{
			//Creates a schedule and adds employees in it
			List<EmployeeSchedule> employeeSchedules = new ArrayList<EmployeeSchedule>();
			TableItem[] selectedEmployee = _tableViewer.getTable().getItems();
			for(TableItem employeeScheduleItem : selectedEmployee)
			{
				EmployeeSchedule employeeSchedule = (EmployeeSchedule)employeeScheduleItem.getData();
				employeeSchedules.add(employeeSchedule);
			}
			
			Schedule schedule = new Schedule();
			schedule.setEmployeeScheduleList(employeeSchedules);
			
			ScheduleJpaController scheduleDao = new ScheduleJpaController();
			scheduleDao.create(schedule);	
		}
		
	}

	@Override
	public void widgetDefaultSelected(SelectionEvent e) {
		// TODO Auto-generated method stub
		
	}
	
	/*
	 * Loads employee schedule to schedule combo
	 */
	private void loadModel(Schedule schedule)
	{
		List<EmployeeSchedule> employeeSchedules = new ArrayList<EmployeeSchedule>();
		employeeSchedules = schedule.getEmployeeScheduleList();

		_tableViewer.setInput(employeeSchedules);
		_tableViewer.refresh();
	}
	
	@Override
	public void setFocus() {
		// TODO Auto-generated method stub

	}
}